package com.yehun.utils;

import com.yehun.enums.BaseEnum;
import com.yehun.model.SelectItem;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.EnumSet;
import java.util.LinkedList;
import java.util.List;

/**
 * 获取枚举
 * Created by Genius on 2017/4/13 0013.
 */
public class EnumUtils {

    private final static Logger logger = LoggerFactory.getLogger(EnumUtils.class);

    public static <T extends BaseEnum> List<SelectItem> getSelect(Class<T> type) {
        List<SelectItem> items = new LinkedList<>();
        T[] array = type.getEnumConstants();
        for (T e : array) {
            items.add(new SelectItem(e.getValue() == Constant.Default.ValueInt ? "" : e.getValue().toString(), e.getText()));
        }
        logger.info("EnumUtils.getSelect, items={}", items.toString());
        return items;
    }

    public static <T extends BaseEnum> List<SelectItem> getSelect(Class<T> type, int value) {
        List<SelectItem> items = new LinkedList<>();
        T[] array = type.getEnumConstants();
        for (T e : array) {
            items.add(new SelectItem(e.getValue().toString(), e.getText(), e.getValue().equals(value)));
        }
        return items;
    }

    public static <T extends BaseEnum> List<SelectItem> getSelect(Class<T> type, T value) {
        if (value == null) {
            return getSelect(type);
        }
        List<SelectItem> items = new LinkedList<>();
        T[] array = type.getEnumConstants();
        for (T e : array) {
            items.add(new SelectItem(e.getValue().toString(), e.getText(), e.getValue().equals(value.getValue())));
        }
        logger.info("EnumUtils.getSelect, items={}", items.toString());
        return items;
    }

    @SuppressWarnings("all")
//    public static <T extends BaseEnum> T getEnum(Class<T> type, int value) throws ClassNotFoundException {
//        Class<Enum> clazz = (Class<Enum>) Class.forName(type.getName());
//        Enum[] objects = clazz.getEnumConstants();
//        for (Enum object : objects) {
//            BaseEnum data = (BaseEnum) object;
//            if (data.getValue().equals(value)) {
//                return (T) object;
//            }
//        }
//        return null;
//    }


    public static <T extends BaseEnum> T getEnum(Class<T> type, int value) {
        T[] array = type.getEnumConstants();
        if(array == null || array.length <= 0){
            return null;
        }
        for (T t : array) {
            if(t.getValue().equals(value)) {
                return t;
            }
        }
        return null;
    }

    public static <T extends Enum<T> & BaseEnum, K> T get(Class<T> type, K value) {
        EnumSet<T> set = EnumSet.allOf(type);
        if(set.size() <= 0){
            return null;
        }
        for(T t: set){
            if(t.getValue().equals(value)){
                return t;
            }
        }
        return null;
    }

}
